<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
use app\common\model\User as UserModel;
use app\common\model\DictData;

class User extends AdminBase
{
    /**
     * 用户列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }

    /**
     * 用户列表JSON
     * @param string $limit
     */
    public function index_json($limit='15')
    {
        $param = $this->request->param();
        $model = new UserModel();
        if (isset($param['keywords']) and $param['keywords'] !='') {
            $keywords = $param['keywords'];
            $model = $model->where('name','like','%'.$keywords.'%')->whereOr('mobile','like','%'.$keywords.'%');
        }
        $list = $model->order('id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = UserModel::create($param);
            if ($result == true) {
                insert_admin_log('添加了用户');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save',[
            'tags'  => DictData::where('dict_id',9)->where('status','1')->order('sort_order desc,id desc')->column('name,name as value')
        ]);
    }

    /**
     * 编辑用户
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param  = $this->request->param();
            //更新数据
            $resule = UserModel::update($param,['id'=>$param['id']]);
            cache('user'.$param['id'],NULL);
            if ( $resule == true) {
                insert_admin_log('修改了用户');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data = UserModel::where('id', input('id'))->find();
        $data['tags'] = explode(',', $data['tags']);
        foreach ($data['tags'] as $k=>$r){
            $t[$k] = "'".$r."'";
        }
        $data['tags'] = implode(',', $t);
        
        $tags = DictData::where('dict_id',9)->where('status','1')->order('sort_order desc,id desc')->column('name,name as value');
        return $this->fetch('save', [
            'data'  => $data,
            'tags'  => $tags
        ]);
    }

    /**
     * 删除用户
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            UserModel::destroy($param['id'],true);
            UserModel::del_all($param['id']);
            cache('user'.$param['id'],NULL);
            insert_admin_log('删除了用户');
            $this->success('删除成功');
        }
    }
    
}
